//
//  MyMessageViewController.m
//  KuWoCan
//
//  Created by hwd on 17/3/3.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "MyMessageViewController.h"
#import "ImageCell.h"
#import "ChinaPlckerView.h"
#import "LabTextFieldCell.h"
#import "NWLoginRequest.h"
#import "LoginUserModel.h"
#import "MyViewController.h"
#import "UIButton+WebCache.h"
#import "MySpecialSignVC.h"
#import "MBProgressHUD.h"
#import "AdressTableViewCell.h"

@interface MyMessageViewController ()<UITableViewDelegate,UITableViewDataSource,ChinaPlckerViewDelegate>
{
    TPKeyboardAvoidingTableView *_tableV;
    UIImage *photoImage;
    UIImage *photoImage2;
}

@property (nonatomic,strong) LoginUserModel *infoModel;

/**
 列表内容保存字典
 */
@property (nonatomic,strong) NSMutableDictionary *paraDic;
/** 用此ID调用修改用户资料接口 */
@property (nonatomic, copy) NSString *changeUserInfoID;
@property (nonatomic, copy) NSArray *titleArr;
@property (nonatomic, copy) NSArray *keyArr;

@end

@implementation MyMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([[CommonTool getLastViewControllerWithCurrentViewController:self] isKindOfClass:[MyViewController class]])
    {
        _isFirstWrite = NO;
    }
    //把相片存在了本地 便于修改 直接移除 否则有照片提交为空（或者将本地的加入字典）
    [NSUserDefaults retrieveObjectForKey:kUserInfo_BusinessLicense];
    [NSUserDefaults retrieveObjectForKey:kUserInfo_FoodCertificate];
    
    NWLoginRequest *request = [[NWLoginRequest alloc] init];
    [request  startRequestGetUserInfoWithId:[Singleton shareInstance].userId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ) {
            self.changeUserInfoID = result[@"id"];
        }
    }];
    self.title = @"我的资料";
    [self.view setBackgroundColor:KwBgColor];
    [self initializeData];
}


- (void)initializeData
{
    _paraDic = [NSMutableDictionary dictionary];
    
    if (!_isFirstWrite)
    {
        for (int i = 0; i < 15; i ++)
        {
            [_paraDic setValue:[NSUserDefaults retrieveObjectForKey:self.keyArr[i]] ?: @"" forKey:self.keyArr[i]];
        }
    }
    else
    {
        for (int i = 0; i < 15; i ++)
        {
            [_paraDic setValue:@"" forKey:self.keyArr[i]];
        }
       
    }
    [self.view addSubview:self.table];
}

-(void)commitInfo
{
    //检测每一行信息.是否有空缺
    if ([self isAllInfo] == YES)
    {
        if ([_paraDic[@"businessLicense"] isEqual:@"url"]) {
            [_paraDic setObject:@"" forKey:@"businessLicense"];
        }
        if ([_paraDic[@"foodCertificate"] isEqual:@"url"]) {
            [_paraDic setObject:@"" forKey:@"foodCertificate"];
        }
        //信息完整可提交
        NWLoginRequest *request = [[NWLoginRequest alloc] init];
        __weak typeof(self) weakSelf = self;
        [request startRequestChangeChangeUserInfoWithDic:_paraDic];
        [request completion:^(id result, NSString *message, id extension, BOOL succ) {
            if (succ) {
                [SVProgressHUD showSuccessWithStatus:@"更新信息成功"];
                //本地数据修改
                [NSUserDefaults saveObject:_paraDic[kUserInfo_SalesChannel] forKey:kUserInfo_SalesChannel];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_BankCard] forKey:@"bankCard"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_Brand] forKey:@"brand"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_RealName] forKey:@"realName"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_Car] forKey:@"car"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_Acreage] forKey:@"acreage"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_Teams] forKey:@"teams"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_SalesArea] forKey:@"salesArea"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_RegisteredCapital] forKey:@"registeredCapital"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_FoodCertificate] forKey:@"foodCertificate"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_BankName] forKey:@"bankName"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_Experience] forKey:@"experience"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_Address] forKey:@"address"];
                [NSUserDefaults saveObject:_paraDic[kUserInfo_Phone] forKey:@"phone"];
                //认证状态修改
                [[UserModel getUser] updateUserCertification];
                if (_isFirstWrite) {
                    MySpecialSignVC *adressVC = [[MySpecialSignVC alloc]init];
                    adressVC.isFirstSubmit = YES;
                    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:adressVC.view animated:YES];
                    hud.mode = MBProgressHUDModeText;
                    hud.labelText = @"请填写签名";
                    [hud hide:YES afterDelay:2.f];
                    [weakSelf.navigationController pushViewController:adressVC animated:YES];
                    return ;
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            } else {
                [SVProgressHUD showErrorWithStatus:message];
            }
        }];
       
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"请输入完整信息"];
    }
    
}

- (BOOL)isAllInfo
{
    [self.view endEditing:YES];
    BOOL status = YES;
    [_paraDic setValue:self.changeUserInfoID forKey:kUserInfo_Id];
    if ([_paraDic[@"businessLicense"] isEqual:@""]) {
        [_paraDic setObject:@"url" forKey:@"businessLicense"];
    }
    if ([_paraDic[@"foodCertificate"] isEqual:@""]) {
        [_paraDic setObject:@"url" forKey:@"foodCertificate"];
    }
    NSArray *objArr = [_paraDic allValues];
    if (objArr && objArr.count == 16)
    {
        for (NSString *infoStr in objArr)
        {
            
            if (!infoStr || infoStr.length <= 0 || [CommonTool isEmpty:infoStr] == YES)
            {
                status = NO;
            }
        }
    }
    return status && self.changeUserInfoID;
}

- (UITableView *)table
{
    if (_tableV == nil)
    {
        _tableV = [[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0,0,SCREENW,SCREENH-64) style:UITableViewStyleGrouped];
        _tableV.delegate = self;
        _tableV.dataSource = self;
        _tableV.showsHorizontalScrollIndicator = NO;
        _tableV.showsVerticalScrollIndicator = NO;
        _tableV.separatorStyle = 0;
        _tableV.backgroundColor = [UIColor colorWithHexString:@"#EFF0F5"];
        _tableV.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    }
    return _tableV;
}

#pragma mark - TableView专区

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 15;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 14 || indexPath.row == 13)
    {
        return 150*screenW_6;
    }
    else
    {
        return 60*screenW_6;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 100*screenW_6;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.00001;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 14 || indexPath.row == 13)
    {
        ImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ImageCell"];
        if (cell == nil)
        {
            cell  = [[ImageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        cell.vc = self;
        if(indexPath.row == 13)
        {
            [cell loadCellWithTitle:@"营业执照" Imgae:photoImage];
            cell.type = CellTypeBuness;
            [cell.picBtn sd_setImageWithURL:[NSURL URLWithString:[NSUserDefaults retrieveObjectForKey:kUserInfo_BusinessLicense]] forState:UIControlStateNormal placeholderImage:kImg(@"LOGO")];
            cell.block = ^{
                [_paraDic setValue:[NSUserDefaults retrieveObjectForKey:kUserInfo_BusinessLicense] forKey:kUserInfo_BusinessLicense];
            };
        }
        else
        {
            [cell loadCellWithTitle:@"食品经营许可证" Imgae:photoImage2];
            cell.type = CellTypeFood;
            [cell.picBtn sd_setImageWithURL:[NSURL URLWithString:[NSUserDefaults retrieveObjectForKey:kUserInfo_FoodCertificate]] forState:UIControlStateNormal placeholderImage:kImg(@"LOGO")];
            cell.block = ^{
                [_paraDic setValue:[NSUserDefaults retrieveObjectForKey:kUserInfo_FoodCertificate] forKey:kUserInfo_FoodCertificate];
            };
        }
        return cell;
        
    }
    else
    {
        static NSString *CellIdentifi = @"adiahgoeioagwie";
        if (indexPath.row == 3)
        {
            AdressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifi];
            if (cell == nil) {
                
                cell  = [[AdressTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifi];
            }
            
            NSString *areaStr = [_paraDic objectForKey:kUserInfo_SalesArea];
            areaStr = [areaStr stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
            if (areaStr.length > 0) {
                
                [cell configCellTitle:self.titleArr[indexPath.row] Description:areaStr];
            } else {
                [cell configCellTitle:self.titleArr[indexPath.row] Description:areaStr];
            }
            
            return cell;
        }
        else
        {
            NSString *labTextFieldCell_id = [NSString stringWithFormat:@"LabTextFieldCell%ld%ld",indexPath.section,indexPath.row];
            LabTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:labTextFieldCell_id];
            if (cell == nil)
            {
                cell  = [[LabTextFieldCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:labTextFieldCell_id];
            }
            cell.block = ^(NSString *txt)
            {
                [_paraDic setValue:txt forKey:self.keyArr[indexPath.row]];
            };
//            cell.leftLab.text = [self.titleArr objectAtIndex:indexPath.row];
            cell.constStr = [self.titleArr objectAtIndex:indexPath.row];
//            cell.rightTxtF.text = [_paraDic objectForKey:self.keyArr[indexPath.row]];
             cell.paraStr = [_paraDic objectForKey:self.keyArr[indexPath.row]];
            if (indexPath.row == 0)
            {
                cell.unitLab.hidden = NO;
                cell.unitLab.text = @"平方米";
            }
            else if (indexPath.row == 1)
            {
                cell.unitLab.hidden = NO;
                cell.unitLab.text = @"辆";
            }
            else if (indexPath.row == 2)
            {
                cell.unitLab.hidden = NO;
                cell.unitLab.text = @"人";
            }
            else if (indexPath.row == 6)
            {
                cell.unitLab.hidden = NO;
                cell.unitLab.text = @"年";
            }
            else if (indexPath.row == 7)
            {
                cell.unitLab.hidden = NO;
                cell.unitLab.text = @"万元";
            }
            else
            {
                cell.unitLab.hidden = YES;
            }
            return cell;
        }
        
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 100*screenW_6)];
    footView.backgroundColor = [UIColor whiteColor];
    CanNButton *outBtn = [[CanNButton alloc]initWithFrame:CGRectMake(20*screenW_6,35*screenW_6, SCREENW-40*screenW_6, 45*screenW_6)];
    [outBtn.layer setCornerRadius:5*screenW_6];
    outBtn.layer.masksToBounds = YES;
    [outBtn setTitle:@"提交" forState:UIControlStateNormal];
    outBtn.backgroundColor = [UIColor colorWithHexString:@"479DE4"];
    [footView addSubview:outBtn];
    outBtn.block = ^(CanNButton *btn){
        [self commitInfo];
    };
    return footView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 3)
    {
        [ChinaPlckerView customChinaPicker:self superView:self.view defaultProName:nil defaultCityName:nil defaultAreaName:nil];
    }
}

- (void)chinaPlckerViewDelegateChinaModel:(ChinaArea *)chinaModel
{
    NSString *cityStr = [NSString stringWithFormat:@"%@,%@,%@",chinaModel.provinceModel.NAME,chinaModel.cityModel.NAME,chinaModel.areaModel.NAME];
    [_paraDic setObject:cityStr forKey:kUserInfo_SalesArea];
    
    NSIndexPath *areaIndexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    [_tableV reloadRowsAtIndexPaths:@[areaIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (NSArray *)titleArr {
    if (!_titleArr) {
        _titleArr = [[NSArray alloc]initWithObjects:
                                                     @"仓库面积",
                                                     @"运输车辆",
                                                     @"团队人数",
                                                     @"销售区域",
                                                     @"销售渠道",
                                                     @"经营品牌",
                                                     @"行业经验",
                                                     @"注册资金",
                                                     @"银行名称",
                                                     @"银行卡号",
                                                     @"真实姓名",
                                                     @"地址",
                                                     @"电话",
                                                     @"营业执照",
                                                     @"食品合格证",
                                                     nil];
    }
    return _titleArr;
}

- (NSArray *)keyArr {
    if (!_keyArr) {
        _keyArr = @[
                    kUserInfo_Acreage,
                    kUserInfo_Car,
                    kUserInfo_Teams,
                    kUserInfo_SalesArea,
                    kUserInfo_SalesChannel,
                    kUserInfo_Brand,
                    kUserInfo_Experience,
                    kUserInfo_RegisteredCapital,
                    kUserInfo_BankName,
                    kUserInfo_BankCard,
                    kUserInfo_RealName,
                    kUserInfo_Address,
                    kUserInfo_Phone,
                    kUserInfo_BusinessLicense,
                    kUserInfo_FoodCertificate
                    ];
    }
    return _keyArr;
}

@end
